package dwr.comet;

import java.util.LinkedList;
import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;
import org.directwebremoting.Browser;
import org.directwebremoting.ScriptSessions;

/**
 *
 */
public class GroupEvent {

    private final LinkedList<Message> messages = new LinkedList<Message>();

    public void fireEvent(String event, String data, String widgetId)
            throws java.io.IOException {
        WebContext ctx = WebContextFactory.get();
        final String page = ctx.getCurrentPage();
        String user = ctx.getHttpServletRequest().getHeader("username");
        String group = ctx.getHttpServletRequest().getHeader("group");
        if (user != null && group != null) {

            messages.addFirst(new Message(user, group, widgetId, event, data));
            while (messages.size() > 10) {
                messages.removeLast();
            }
        }

        Browser.withPage(page, new Runnable() {

            public void run() {
                if (page.contains(messages.element().getGroup())) {
                    ScriptSessions.addFunctionCall("receiveEvent", messages.element());
                }
            }
        });

    }

    public class Message {

        private String user;
        private String data;
        private String group;
        private String event;
        private String widgetId;
        private long time;

        public Message(String user, String group, String widgetId, String event, String data) {
            this.user = user;
            this.data = data;
            this.widgetId = widgetId;
            this.event = event;
            this.group = group;
            this.time = System.currentTimeMillis();
        }

        public String getData() {
            return data;
        }

        public String getUser() {
            return user;
        }

        public String getGroup() {
            return group;
        }

        public String getEvent() {
            return event;
        }

        public String getWidgetId() {
            return widgetId;
        }

        public long getTime() {
            return time;
        }
    }
}
